package com.example.geoaimavlink_android.activity.fragment

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.example.geoaimavlink_android.R
import com.geoai.mavlink.geoainet.base.mavlinkcore.controller.StarLinkClientManager
import kotlinx.android.synthetic.main.frag_diagnostic.tv_diagnostic_msg

class DiagnosticFragment: BaseFragment() {

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return View.inflate(context, R.layout.frag_diagnostic, null)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initSDK()
    }

    private fun initSDK() {
        msdkInfoVm.msdkInfo.observe(viewLifecycleOwner) { msdkInfo ->
            if (msdkInfo.isAircraftConnected.not()) return@observe
            StarLinkClientManager.getInstance().getProduct(msdkInfo.droneID)?.flyControllerManager?.setDiagnosticsStateListener { diagnostics ->
                tv_diagnostic_msg?.text = diagnostics.toList().joinToString {
                    "{\"code\": ${it.alertCode}, " +
                            "\"name\": ${it.name}, " +
                            "\"index\": ${it.alertIndex}, " +
                            "\"level\": ${it.alertLevel}, " +
                            "\"hold\": ${it.holdTime}, \n" +
                            "\"msg\": ${it.message}, " +
                            "\"ts\": ${it.timestamp}}\n"
                }
            }
        }
    }

    override fun onDestroyView() {
        StarLinkClientManager.getInstance().getProduct(msdkInfoVm.msdkInfo.value?.droneID?:1)?.flyControllerManager?.setDiagnosticsStateListener(null)
        msdkInfoVm.msdkInfo.removeObservers(viewLifecycleOwner)
        super.onDestroyView()
    }
}